import sys

from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QGridLayout,
    QGroupBox, QLineEdit, QPushButton, QLabel,
    QMessageBox, QFrame
)
from PyQt5.QtCore import Qt
from bank_manage_system.user.client_operations import ClientOperations
from bank_manage_system.gui.login_window import LoginWindow  # 导入登录窗口


# 使用全局样式配置
PRIMARY_COLOR = "#3498db"  # 主题蓝色
SECONDARY_COLOR = "#2ecc71"  # 绿色
WARNING_COLOR = "#f39c12"  # 橙色
DANGER_COLOR = "#e74c3c"  # 红色
BG_COLOR = "#f8f9fa"  # 背景色
TEXT_COLOR = "#2c3e50"  # 文字颜色
ACCENT_COLOR = "#6a5acd"  # 强调色

# 字体配置
HEADER_FONT = QFont("Microsoft YaHei UI", 12, QFont.Bold)
LABEL_FONT = QFont("Microsoft YaHei UI", 10)
BUTTON_FONT = QFont("Microsoft YaHei UI", 10, QFont.Bold)
INPUT_FONT = QFont("Microsoft YaHei UI", 10)


class AccountSettingsTab(QWidget):
    def __init__(self, db, card_id, parent=None):

        super().__init__()
        self.db = db
        self.card_id = card_id
        self.parent = parent  # 保存父窗口引用
        self.client_ops = ClientOperations(db, card_id)
        self.initUI()
        self.apply_styles()

    def initUI(self):
        """初始化界面"""
        main_layout = QVBoxLayout()
        main_layout.setSpacing(20)
        main_layout.setContentsMargins(15, 10, 15, 15)

        # 标题区
        header_frame = QFrame()
        header_layout = QHBoxLayout(header_frame)
        header_layout.setContentsMargins(15, 10, 15, 10)

        title_label = QLabel("账户设置")
        title_label.setFont(HEADER_FONT)
        title_label.setStyleSheet(f"color: {TEXT_COLOR};")

        # 显示部分卡号
        masked_card_id = f"{self.card_id[:6]} ***** {self.card_id[-4:]}"
        card_label = QLabel(masked_card_id)
        card_label.setFont(QFont("Microsoft YaHei UI", 11))
        card_label.setStyleSheet(f"color: {TEXT_COLOR};")

        header_layout.addWidget(title_label)
        header_layout.addWidget(card_label, 1, Qt.AlignLeft)

        main_layout.addWidget(header_frame)

        # ================= 密码修改卡片 =================
        self.password_card = QGroupBox("密码设置")  # 实例变量
        password_layout = QGridLayout(self.password_card)
        password_layout.setVerticalSpacing(15)
        password_layout.setHorizontalSpacing(10)

        # 当前密码
        self.current_password = QLineEdit()
        self.current_password.setEchoMode(QLineEdit.Password)
        self.current_password.setMinimumHeight(35)
        password_layout.addWidget(QLabel("当前密码:"), 0, 0)
        password_layout.addWidget(self.current_password, 0, 1)

        # 新密码
        self.new_password = QLineEdit()
        self.new_password.setEchoMode(QLineEdit.Password)
        self.new_password.setMinimumHeight(35)
        password_layout.addWidget(QLabel("新密码:"), 1, 0)
        password_layout.addWidget(self.new_password, 1, 1)

        # 确认密码
        self.confirm_password = QLineEdit()
        self.confirm_password.setEchoMode(QLineEdit.Password)
        self.confirm_password.setMinimumHeight(35)
        password_layout.addWidget(QLabel("确认密码:"), 2, 0)
        password_layout.addWidget(self.confirm_password, 2, 1)

        # 密码提示标签
        password_tips = QLabel("密码长度应至少8位，包含字母和数字")
        password_tips.setFont(QFont("Microsoft YaHei UI", 9))
        password_tips.setStyleSheet(f"color: {WARNING_COLOR}; margin-top: 10px;")
        password_layout.addWidget(password_tips, 3, 0, 1, 2, Qt.AlignCenter)

        # 修改密码按钮
        self.change_password_btn = QPushButton("修改密码")
        self.change_password_btn.setFont(BUTTON_FONT)
        self.change_password_btn.setMinimumHeight(40)
        self.change_password_btn.clicked.connect(self.change_password)
        password_layout.addWidget(self.change_password_btn, 4, 0, 1, 2)

        main_layout.addWidget(self.password_card)

        # ================= 账户安全卡片 =================
        self.security_card = QGroupBox("账户安全")  # 添加 self. 前缀
        security_layout = QVBoxLayout(self.security_card)
        security_layout.setContentsMargins(15, 10, 15, 20)
        security_layout.setSpacing(15)

        # 安全警告
        warning_label = QLabel("⚠️ 警告：账户挂失操作不可逆转，请谨慎操作！")
        warning_label.setFont(BUTTON_FONT)
        warning_label.setStyleSheet(f"""
            background-color: {DANGER_COLOR}8;
            color: {DANGER_COLOR};
            padding: 10px;
            border-radius: 6px;
            border: 1px solid {DANGER_COLOR}30;
        """)
        warning_label.setAlignment(Qt.AlignCenter)
        security_layout.addWidget(warning_label)

        # 挂失说明
        loss_label = QLabel(
            "账户挂失后:\n"
            "- 账户将被立即冻结，无法进行任何交易\n"
            "- 您需要携带有效身份证件到柜台办理解挂手续\n"
            "- 解挂后账户会重置安全状态"
        )
        loss_label.setFont(QFont("Microsoft YaHei UI", 9))
        loss_label.setStyleSheet(f"color: {TEXT_COLOR};")
        security_layout.addWidget(loss_label)

        # 挂失按钮
        self.report_loss_btn = QPushButton("挂失账户")
        self.report_loss_btn.setFont(BUTTON_FONT)
        self.report_loss_btn.setMinimumHeight(45)
        self.report_loss_btn.clicked.connect(self.report_loss)
        security_layout.addWidget(self.report_loss_btn)

        main_layout.addWidget(self.security_card)

        # 状态标签（底部居中）
        self.status_label = QLabel("")
        self.status_label.setFont(LABEL_FONT)
        self.status_label.setAlignment(Qt.AlignCenter)
        self.status_label.setStyleSheet("margin-top: 10px; min-height: 30px;")
        main_layout.addWidget(self.status_label)

        self.setLayout(main_layout)

    def apply_styles(self):
        """应用样式表"""
        self.setStyleSheet(f"""
            QGroupBox {{
                border: 1px solid {PRIMARY_COLOR}40;
                border-radius: 8px;
                margin-top: 1em;
                padding-top: 15px;
                background-color: white;
            }}

            QGroupBox::title {{
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 0px 10px;
                background-color: transparent;
                color: {PRIMARY_COLOR};
                border-radius: 4px;
                font-weight: bold;
                font-size: 11pt;
            }}

            QLineEdit {{
                background-color: white;
                border: 1px solid #ced4da;
                border-radius: 6px;
                padding: 8px 12px;
                font-size: 11pt;
            }}

            QLineEdit:focus {{
                border: 2px solid {PRIMARY_COLOR};
                background-color: {PRIMARY_COLOR}08;
            }}

            QPushButton {{
                border-radius: 6px;
                padding: 8px 16px;
                font-weight: bold;
                min-height: 35px;
            }}

            #passwordCard QPushButton {{
                background-color: {PRIMARY_COLOR};
                color: white;
            }}

            #passwordCard QPushButton:hover {{
                background-color: {PRIMARY_COLOR}cc;
            }}

            #securityCard QPushButton {{
                background-color: {DANGER_COLOR};
                color: white;
            }}

            #securityCard QPushButton:hover {{
                background-color: {DANGER_COLOR}cc;
            }}
        """)

        # 应用卡片标识
        self.password_card.setObjectName("passwordCard")
        self.security_card.setObjectName("securityCard")

    def change_password(self):
        """修改密码"""
        old_pass = self.current_password.text().strip()
        new_pass = self.new_password.text().strip()
        confirm_pass = self.confirm_password.text().strip()

        # 验证输入
        errors = []
        if not old_pass:
            errors.append("请输入当前密码")
        if not new_pass:
            errors.append("请输入新密码")
        if not confirm_pass:
            errors.append("请确认新密码")

        if errors:
            self.status_label.setText("\n".join(errors))
            self.status_label.setStyleSheet(f"color: {WARNING_COLOR};")
            return

        # 验证密码规则
        if len(new_pass) < 8:
            self.status_label.setText("密码长度至少8位")
            self.status_label.setStyleSheet(f"color: {WARNING_COLOR};")
            return

        if not any(char.isdigit() for char in new_pass) or not any(char.isalpha() for char in new_pass):
            self.status_label.setText("密码需包含字母和数字")
            self.status_label.setStyleSheet(f"color: {WARNING_COLOR};")
            return

        # 确认密码
        if new_pass != confirm_pass:
            self.status_label.setText("新密码与确认密码不匹配")
            self.status_label.setStyleSheet(f"color: {WARNING_COLOR};")
            return

        # 执行修改
        result = self.client_ops.change_password(old_pass, new_pass)

        # 显示结果
        if result.get('success', False):
            self.status_label.setText("密码修改成功")
            self.status_label.setStyleSheet(f"color: {SECONDARY_COLOR};")
            # 清空密码框
            self.current_password.clear()
            self.new_password.clear()
            self.confirm_password.clear()
        else:
            self.status_label.setText(result.get('message', '修改失败'))
            self.status_label.setStyleSheet(f"color: {WARNING_COLOR};")

    def report_loss(self):
        """挂失账户"""
        # 确认对话框
        confirm_box = QMessageBox(self)
        confirm_box.setWindowTitle("确认账户挂失")
        confirm_box.setIcon(QMessageBox.Warning)
        confirm_box.setText(
            "<b>确定要挂失此账户吗？</b><br>"
            "挂失后将无法进行任何操作！"
        )
        confirm_box.setInformativeText(
            "请确保已在银行柜台获取必要文件后再执行此操作！"
        )

        # 自定义按钮
        confirm_box.addButton("确认挂失", QMessageBox.YesRole)
        cancel_btn = confirm_box.addButton("取消", QMessageBox.RejectRole)
        cancel_btn.setStyleSheet(f"background-color: {SECONDARY_COLOR}; color: white;")

        confirm_box.exec_()

        if confirm_box.clickedButton() != cancel_btn:
            result = self.client_ops.report_loss()

            if result.get('success', False):
                # 显示成功消息
                success_box = QMessageBox(self)
                success_box.setWindowTitle("挂失成功")
                success_box.setIcon(QMessageBox.Information)
                success_box.setText(
                    f"<b>账户 {self.card_id} 已成功挂失！</b>"
                )
                success_box.setInformativeText(
                    "系统将在10秒内自动退出，请携带有效身份证件到银行柜台办理解挂手续。"
                )
                success_box.addButton("立即退出", QMessageBox.AcceptRole)
                success_box.exec_()

                # 跳转到登录窗口
                self.jump_to_login()
            else:
                self.status_label.setText(result.get('message', '挂失失败'))
                self.status_label.setStyleSheet(f"color: {DANGER_COLOR};")

    def jump_to_login(self):
        """跳转到登录窗口"""
        if self.parent:
            # 关闭当前主窗口
            self.parent.close()


        sys.exit(0)
        self.close()